<template>
  <div class="myInfo">
    <div class="title">
      <span>汇总数据查询</span>
      <input type="text" style="margin:0 15px;width:300px" v-model="searchStoreId" placeholder="请输入网吧店铺id(storeId)"/>
      <span class="btn" @click="getType">获取分类</span>
      <div class="type-sel" @click.stop="showType=!showType">
          <span class="tit">{{isSelAll?'全部':(selType.length>0?`${selType[0]}...`:'分类选择')}}</span>
          <div class="type-item" v-if="showType" @click.stop="">
              <ul>
                  <li>
                      <div>
                      <label><input type="checkbox" :value="'ALL'" @click.stop="selAll" v-model="isSelAll" />全部</label>
                      </div>
                      <div v-for="(item,index) in options" :key="index">
                          <label><input type="checkbox" v-model="selType" :value="item.value" />{{item.label}}</label>
                      </div> 
                  </li>
              </ul>
          </div>
      </div>
      <el-date-picker
      v-model="valueForMonth"
      format="yyyy 年 MM 月"
      :picker-options="pickerOptions0"
      type="month"
      class="dateTime month-sel"
      placeholder="选择月">
      </el-date-picker>
      <span class="btn" @click="getData">查询</span>
    </div>
    <div class="store">
      <table class="head">
        <th width="10%">序号</th>
        <th width="20%">商品名</th>
        <th width="10%">数量</th>
        <th width="15%">售价</th>
        <!-- <th width="15%">一级分类</th> -->
        <th width="15%">分类名</th>
        <th width="15%">总计</th>
      </table>
      <table class="body">
        <tr v-for="(item,index) in lastData" :key="index">
          <td width="10%">{{index+1}}</td>
          <td width="20%">{{item.name}}</td>
          <td width="10%">{{item.qty}}</td>
          <td width="15%">{{item.salesPrice}}</td>
          <!-- <td width="15%">{{item.parentTypeName}}</td> -->
          <td width="15%">{{item.typeName}}</td>
          <td width="15%">{{item.amount}}</td>
        </tr>
      </table>
    </div>
    <div class="change-goods-info" v-if="showChangeGift" @click="showChangeGift=false">
      <div class="goods-wrap" @click.stop="">
        <div class="item goods-name">
          <input type="text" placeholder="请输入商品名字" v-model="nowSelGift.name" />
        </div>
        <div class="item goods-price">
          <input type="text" placeholder="请输入商品价格" v-model="nowSelGift.salesPrice" />
        </div>
        <div class="item goods-img">
          <img v-if="!giftImgUrl" :src="nowSelGift.imageURL" alt="">
          <img v-else :src="giftImgUrl" alt="">
          <div class="upload-img">
            <span>选择图片</span>
            <input type="file" @change="cropImg" name="logo" id="">
          </div>
        </div>
        <div class="item confirm">
          <button @click="save">确定</button>
        </div>
      </div>
    </div>
    <img-crop v-if="showCrop" :oldImg="oldImgBase64" :curCropW="curCropW" :curCropH="curCropH" :curStoreId="curStoreId" @closeImgCrop="showCrop=false" @getCropImgBase="getCropImgBase"></img-crop>
    <table id="scrollBox" style="display:none"> 
    </table>
    <span class="btn right" style="margin-top:10px" @click="excel">导出excel</span>
  </div>
</template>

<script>
import imgCrop from "./../components/imgCrop/imgCrop.vue";
import {BASE_URL} from "./../../urlConfig/index";

export default {
  components: { imgCrop },
  data() {
    return {
      isSelAll:true,
      selType:[],
      showType:false,
      searchStoreId:'',
      pickerOptions0: {
      //时间禁用,今天以后的时间禁用。
          disabledDate(time) {
            let month = new Date(Date.now()).getMonth() + 1;
            let lastMonth = month - 3;
            let year = new Date(Date.now()).getFullYear();
            if(lastMonth<1){
              year--;
            }
            lastMonth = (month - 3) <=0?12:(month-3);
            let nowDate = new Date(`${year}/${lastMonth}`).Format("yyyy/MM/dd");
            return time.getTime() > new Date(nowDate).getTime();
          }
      },
      valueForMonth:"",
      lastData: [],
      size: 10,
      totalElements: 0,
      nowSelGift: {},
      showChangeGift: false,
      showCrop: false,
      oldImgBase64: "",
      curCropW: 600, // 裁剪宽度
      curCropH: 600, // 裁剪高度
      giftImgUrl: "",
      curStoreId: "574b59ef-b19c-11e7-9233-37891743d141",
      allQtyForMonth:0,
      allAmountForMonth:0,
      options:[] 
    };
  },
  watch:{
      selType(val){
          console.log(val)
          if(val.length == this.options.length){
              this.isSelAll = true;
          }else{
              this.isSelAll = false;
          }
      },
  },
  methods: {
    getType(){
      if(!this.searchStoreId){
        this.$message({
          message: "storeId没传",
          type: "error"
        });
        return;
      }
      this.$http({
        url: BASE_URL+"v1/call/get-type",
        method: "GET",
        params:{
          storeId:this.searchStoreId
        }
      }).then(res=>{
        for (var i = 0; i < res.data.length; i++) {
            let obj={
                value:res.data[i].name,
                label:res.data[i].name
            }
            this.selType.push(res.data[i].name);
            this.options.push(obj);
        }
      })
    },
    selAll(){
        this.isSelAll = !this.isSelAll;
        if(this.isSelAll){
            let selType = [];
            for (let i = 0; i < this.options.length; i++) {
                selType.push(this.options[i].value);
            }
            this.selType = selType;
        }else{
            this.selType = [];
        }
        
    },
    getData(){
      let month = new Date(this.valueForMonth).Format("yyyyMM");
      let begin = new Date(this.valueForMonth).Format("yyyy/MM");
      begin = new Date(begin).Format("yyyy-MM-dd");
      let nextMonth = new Date(this.valueForMonth).getMonth() + 2;
      let year = new Date(this.valueForMonth).getFullYear();
      if(nextMonth>12){
        year++;
      }
      nextMonth = nextMonth>12?1:nextMonth;
      console.log(`${year}/${nextMonth}`);
      let endTimeStr = `${year}/${nextMonth}`;
      let end = new Date(endTimeStr).getTime() - 1000*60*60*24;
      end = new Date(end).Format("yyyy-MM-dd");
      if(!this.searchStoreId){
        this.$message({
          message: "storeId没传",
          type: "error"
        });
        return;
      }
      let typeName = this.selType;
      if(!typeName.length){
        typeName = [];
      }
      this.$http({
        url: BASE_URL+"v1/call/get-month-sales",
        method:"POST",
        data:{
          storeId:this.searchStoreId,
          month,
          begin:`${begin} 00:00:00`,
          end:`${end} 23:59:59`,
          typeName
        }
      }).then(res=>{
        this.showType = false;
        if(!res.data.length){
          this.$message({
            message: "无数据",
            type: "error"
          });
        }
        this.lastData = res.data;
        let allAmount = 0;
        let allQty = 0;
        for(let i=0;i<res.data.length;i++){
          allAmount+=res.data[i].amount;
          allQty+=res.data[i].qty;
        }
        this.allAmountForMonth = allAmount;
        this.allQtyForMonth = allQty; 
      })
    },
    //导出按钮
    excel(){
        let data,amount,qty;
        
        if ( !this.lastData[0].name ) {
            this.$message({
                message: '无数据可导出',
                type: 'error'
            })
            return;
        }
        data = this.lastData;
        amount = this.allAmountForMonth;
        qty = this.allQtyForMonth;
        let num =0,price=0;
        let html = '<tr>'+  
                        '<td style="font-size:18px">商品名称</td>'+
                        '<td style="font-size:18px">售价</td>'+
                        '<td style="font-size:18px">数量</td>'+ 
                        // '<td style="font-size:18px">一级分类</td>'+ 
                        '<td style="font-size:18px">分类名</td>'+ 
                        '<td style="font-size:18px">总计</td>'+
                    '</tr>'
                for(var i=0;i<data.length;i++){
                    if ( !data[i].name ) {
                        continue;
                    }

                    num+=data[i].qty;
                    price+=data[i].amount;
                    html  +='<tr>'+
                                '<td>'+data[i].name+'</td>'+
                                '<td>'+data[i].salesPrice+'</td>'+ 
                                '<td>'+data[i].qty+'</td>'+ 
                                // '<td>'+data[i].parentTypeName+'</td>'+ 
                                '<td>'+data[i].typeName+'</td>'+ 
                                '<td>'+data[i].amount+'</td>'+ 
                            '</tr>'
                }
            html += 
                    '<tr>'+
                        '<td style="font-size:16px">总金额</td>'+
                        '<td></td>'+ 
                        '<td></td>'+ 
                        '<td>'+amount+'</td>'+ 
                    '</tr>'+
                    '<tr>'+
                        '<td style="font-size:16px">总数量</td>'+
                        '<td></td>'+ 
                        '<td></td>'+ 
                        '<td>'+qty+'</td>'+ 
                    '</tr>'
        document.getElementById('scrollBox').innerHTML = html;
        window.method5(scrollBox);
    },
    //上传图片
    cropImg(e) {
      let reader = new FileReader();
      let that = this;
      let fileObj = e.target.files[0];

      if (e.target.files.length == 0) {
        return false;
      }

      // 判断图片大小
      if (fileObj.size > this.coverImgMaxSize) {
        this.errorMsg = "上传图片的大小不能超过5MB";
        this.openErrorTip = true;
        this.$message({
          message: "上传图片的大小不能超过5MB",
          type: "error"
        });
        return false;
      }

      reader.onload = (function(file) {
        return function(e) {
          let _this = this; // 缓存当前this
          let img = new Image();
          img.src = this.result;
          img.onload = function() {
            let imgBase64 = _this.result; //获得图片的base64的数据
            that.oldImgBase64 = imgBase64;
            that.showCrop = true;
          };
        };
      })(e.target.files[0]);

      reader.readAsDataURL(e.target.files[0]);
    },
    getCropImgBase(imgUrl) {
      this.giftImgUrl = imgUrl;
    },
    handleCurrentChange(val) {
      this.getAllData(val - 1);
      this.curPage = val;
    },
    doDeal(item) {
      this.nowSelGift = JSON.stringify(item);
      this.nowSelGift = JSON.parse(this.nowSelGift);
      this.showChangeGift = true;
      return;
      this.$http({
        url: BASE_URL+"v1/call/update-storeAccount",
        method: "POST",
        data: {
          id: item.id,
          accounting: 1
        }
      }).then(res => {
        console.log(res);
        this.$message({
          message: "划账成功",
          type: "success"
        });
        this.getAllData(this.curPage - 1);
      });
    },
    save() {
      let giftImgUrl = this.giftImgUrl ? this.giftImgUrl:this.nowSelGift.imageURL;
      this.$http({
        url: BASE_URL+"v1/call/update-gift",
        method: "POST",
        data: {
          id: this.nowSelGift.id,
          name: this.nowSelGift.name,
          productUrl: giftImgUrl,
          salesPrice: this.nowSelGift.salesPrice
        }
      }).then(res => {
        console.log(res);
        if (res.data.result.code == 200) {
          this.$message({
            message: res.data.result.msg,
            type: "success"
          });
          this.showChangeGift = false;
          this.getAllData();
        }
      });
    },
    // getAllData() {
    //   this.$http({
    //     url: BASE_URL+"v1/call/find-allGift",
    //     method: "GET"
    //   }).then(res => {
    //     console.log(res);
    //     this.lastData = res.data;
    //   });
    // }
  },
  created: function() {},
  mounted() {
    let month = new Date().getMonth() + 1;
    let lastMonth = month - 3;
    let year = new Date().getFullYear();
    if(lastMonth<1){
      year--;
    }
    lastMonth = (month - 3) <=0?12:(month-3);
    let nowDate = new Date(`${year}/${lastMonth}`).Format("yyyy/MM/dd");
    console.log(nowDate);
    this.valueForMonth = new Date(nowDate).getTime();
  }
};
</script>
<style lang="scss" scoped>
@import "./lastData.scss";
</style>
